package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.entity.ContractDO;
import com.ruoyi.system.entity.ContractFile;
import com.ruoyi.system.mapper.ContractFileMapper;
import com.ruoyi.system.service.ContractFileService;
import com.ruoyi.system.service.ContractService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 合同文件关联表 服务实现类
 */
@Service
public class ContractFileServiceImpl extends ServiceImpl<ContractFileMapper, ContractFile> implements ContractFileService {

    @Resource
    private ContractService contractService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<ContractFile> contractFiles) {
        if (contractFiles == null || contractFiles.isEmpty()) {
            return;
        }
        super.saveBatch(contractFiles);
    }

    @Override
    public List<ContractFile> getByContractId(Long contractId) {
        return baseMapper.selectByContractId(contractId);
    }

    @Override
    public List<ContractFile> getByContractIdAndType(Long contractId, Integer businessType) {
        return baseMapper.selectByContractIdAndType(contractId, businessType);
    }

    @Override
    public void removeByContractId(Long contractId) {
        this.lambdaUpdate()
                .eq(ContractFile::getContractId, contractId)
                .remove();
    }

    @Override
    public boolean removeByFileId(Long fileId) {
        ContractFile contractFile = this.lambdaQuery()
                .eq(ContractFile::getId, fileId)
                .eq(ContractFile::getIsDelete, 0)
                .one();
        if (contractFile == null) {
            throw new ServiceException("文件不存在");
        }
        ContractDO contractDO = contractService.lambdaQuery()
                .eq(ContractDO::getId, contractFile.getContractId())
                .eq(ContractDO::getIsDeleted, 0)
                .one();
        if (contractDO == null) {
            throw new ServiceException("合同不存在");
        }

        if (contractDO.getAuditStatus() == 1) {
            throw new ServiceException("合同已审核，不能删除文件");
        }
        return baseMapper.deleteById(fileId) > 0;
    }
}